class Admin::ProductAccessoriesController < Admin::AdminController
  before_filter :load_product
  
  filter_access_to :show, :available, :require => :read
  filter_access_to :remove, :select,  :require => :edit

  def show
  end

  def available
    @available_accessories = []

    unless params[:query].blank?
      @available_accessories = Variant.group("products.id").includes(:product).where("products.state != 'deleted' AND products.presentation LIKE ?", "%#{params[:query]}%")
      @available_accessories.delete_if {|accessory| @product.accessories.include?(accessory)} #|| accessory == @product.master}
    end

    respond_to do |format|
      format.html
      format.js {render :layout => false}
    end
  end

  def remove
    Relation.find(:first, :conditions => {:related_to_id => params[:id], :relatable_id => params[:product_id]}).destroy

    @accessories = @product.accessories
  end

  def select
    @product.accessories << Variant.find(params[:id])
    @product.save

    @accessories = @product.accessories
  end

  private
  def load_product
    @product = Product.find(params[:product_id])
  end
end
